package ru.pb.game.data.xml.parsers;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import ru.pb.game.data.templates.AbstractItemTemplate;
import ru.pb.game.data.templates.ArmorTemplate;
import ru.pb.game.data.templates.CuponTemplate;
import ru.pb.game.data.templates.WeaponTemplate;
import ru.pb.game.data.xml.holders.ItemHolder;
import ru.pb.global.utils.ParserUtils;
import ru.pb.global.utils.StatsSet;
import ru.pb.global.xml.parsers.AbstractDirParser;

/**
 * @author Felixx
 */
public final class ItemParser extends AbstractDirParser<ItemHolder>
{
	private static ItemParser _instance;
	private int _currentItemId;

	public static ItemParser getInstance()
	{
		if(_instance == null)
		{
			_instance = new ItemParser();
		}
		return _instance;
	}

	private ItemParser()
	{
		super("./data/items/", "template.xml", ItemHolder.getInstance());
	}

	@Override
	protected void readData(Node doc, String file) throws Exception
	{
		super.readData(doc, file);

		if("list".equalsIgnoreCase(doc.getNodeName()))
		{
			for(Node sa = doc.getFirstChild(); sa != null; sa = sa.getNextSibling())
			{
				if("weapon".equalsIgnoreCase(sa.getNodeName()) || "armor".equalsIgnoreCase(sa.getNodeName()) || "cupon".equalsIgnoreCase(sa.getNodeName()))
				{
					parseItem(sa.getNodeName(), sa);
				}
			}
		}
	}

	public void parseItem(String type, Node sa) throws Exception
	{
		NamedNodeMap map = sa.getAttributes();

		StatsSet set = new StatsSet();
		set.set("id", ParserUtils.intValue(map.getNamedItem("id")));
		set.set("name", ParserUtils.stringValue(map.getNamedItem("name")));

		_currentItemId = set.getInt("id");

		for(Node s1 = sa.getFirstChild(); s1 != null; s1 = s1.getNextSibling())
		{
			if("set".equalsIgnoreCase(s1.getNodeName()))
			{
				map = s1.getAttributes();
				set.set(map.getNamedItem("name").getNodeValue(), map.getNamedItem("val").getNodeValue());
			}
		}

		AbstractItemTemplate template = null;

		try
		{
			if(type.equalsIgnoreCase("weapon"))
			{
				template = new WeaponTemplate(set);
			}
			else if(type.equalsIgnoreCase("armor"))
			{
				template = new ArmorTemplate(set);
			}
			else if(type.equalsIgnoreCase("cupon"))
			{
				template = new CuponTemplate(set);
			}
		}
		catch(Exception e)
		{
			info("Fail create item: " + _currentItemId, e);
			return;
		}
		getHolder().addTemplate(template);
	}
}